//
//  NSArray+Extension.m
//  YunDaHome-iOS
//
//  Created by 刘权 on 2020/1/15.
//  Copyright © 2020 YunDa. All rights reserved.
//

#import "NSArray+Extension.h"

@implementation NSArray (Extension)

/// 安全地取值，若越界取nil
- (id)j_objectAtIndex:(NSUInteger)index{
    if (index < self.count) {
        return self[index];
    }else{
        return nil;
    }
}

/// 随机返回一个对象 (如果Array空，则返回nil)
- (id)j_randomObject{
    if (self.count) {
        return self[arc4random_uniform((u_int32_t)self.count)];
    }
    return nil;
}


@end

@implementation NSMutableArray (Extension)

/// 安全地追加object
- (void)j_addObject:(id)obj{
    if (obj) {
        [self addObject:obj];
    }
}

/// 追加CGPoint
- (void)j_addPoint:(CGPoint)point{
    [self addObject:NSStringFromCGPoint(point)];
}

/// 追加CGSize
- (void)j_addSize:(CGSize)size{
    [self addObject:NSStringFromCGSize(size)];
}

/// 追加CGRect
- (void)j_addRect:(CGRect)rect{
    [self addObject:NSStringFromCGRect(rect)];
}

/// 在某个位置添加一批对象 (index不能超出范围)
- (void)j_insertObjects:(NSArray *)objects atIndex:(NSUInteger)index{
    NSUInteger i = index;
    for (id obj in objects) {
        [self insertObject:obj atIndex:i++];
    }
}

/// 反转对象顺序，例如 @[ @1, @2, @3 ] -> @[ @3, @2, @1 ].
- (void)j_reverse{
    NSUInteger count = self.count;
    int mid = floor(count / 2.0);
    for (NSUInteger i = 0; i < mid; i++) {
        [self exchangeObjectAtIndex:i withObjectAtIndex:(count - (i + 1))];
    }
}

/// 随机排列对象顺序 (洗牌)
- (void)j_shuffle{
    for (NSUInteger i = self.count; i > 1; i--) {
        [self exchangeObjectAtIndex:(i - 1)
                  withObjectAtIndex:arc4random_uniform((u_int32_t)i)];
    }
}

@end
